<template>
  <div class="property-company-register-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="logo-section">
          <el-icon class="logo-icon"><House /></el-icon>
          <h1 class="system-title">智慧社区管理系统</h1>
        </div>
        <div class="page-title">
          <h2>物业公司注册</h2>
          <p>欢迎注册成为我们的合作伙伴</p>
        </div>
      </div>
    </div>

    <!-- 注册表单 -->
    <div class="register-container">
      <el-card class="register-card" shadow="never">

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="register-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="公司名称" prop="companyName">
                <el-input
                  v-model="formData.companyName"
                  placeholder="请输入公司名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司编码" prop="companyCode">
                <el-input
                  v-model="formData.companyCode"
                  placeholder="由系统自动生成"
                  readonly
                  disabled
                />
                <div class="form-tip">
                  <el-icon><InfoFilled /></el-icon>
                  <span>公司编码由系统自动生成，无需手动输入</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="统一社会信用代码" prop="creditCode">
                <el-input
                  v-model="formData.creditCode"
                  placeholder="请输入统一社会信用代码"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="营业执照号" prop="businessLicense">
                <el-input
                  v-model="formData.businessLicense"
                  placeholder="请输入营业执照号"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="法定代表人" prop="legalRepresentative">
                <el-input
                  v-model="formData.legalRepresentative"
                  placeholder="请输入法定代表人"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="成立日期" prop="establishedDate">
                <el-date-picker
                  v-model="formData.establishedDate"
                  type="date"
                  placeholder="请选择成立日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="注册资本(万元)" prop="registeredCapital">
                <el-input-number
                  v-model="formData.registeredCapital"
                  :min="0"
                  :precision="2"
                  placeholder="请输入注册资本"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="资质等级" prop="qualificationLevel">
                <el-select
                  v-model="formData.qualificationLevel"
                  placeholder="请选择资质等级"
                  style="width: 100%"
                >
                  <el-option label="一级" value="一级" />
                  <el-option label="二级" value="二级" />
                  <el-option label="三级" value="三级" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="公司地址" prop="address">
            <el-input
              v-model="formData.address"
              placeholder="请输入公司地址"
              clearable
            />
          </el-form-item>

          <el-form-item label="服务范围" prop="serviceScope">
            <el-input
              v-model="formData.serviceScope"
              type="textarea"
              :rows="3"
              placeholder="请输入服务范围"
            />
          </el-form-item>

          <el-form-item label="公司简介" prop="introduction">
            <el-input
              v-model="formData.introduction"
              type="textarea"
              :rows="4"
              placeholder="请输入公司简介"
            />
          </el-form-item>
        </div>

        <!-- 联系信息 -->
        <div class="form-section">
          <h3 class="section-title">联系信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactPerson">
                <el-input
                  v-model="formData.contactPerson"
                  placeholder="请输入联系人"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input
                  v-model="formData.contactPhone"
                  placeholder="请输入联系电话"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系邮箱" prop="contactEmail">
                <el-input
                  v-model="formData.contactEmail"
                  placeholder="请输入联系邮箱"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱地址" prop="email">
                <el-input
                  v-model="formData.email"
                  placeholder="请输入邮箱地址"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="营业时间" prop="businessHours">
                <el-input
                  v-model="formData.businessHours"
                  placeholder="请输入营业时间"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务热线" prop="serviceHotline">
                <el-input
                  v-model="formData.serviceHotline"
                  placeholder="请输入服务热线"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 支付信息 -->
        <div class="form-section">
          <h3 class="section-title">支付信息</h3>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="收款账户" prop="paymentAccount">
                <el-input
                  v-model="formData.paymentAccount"
                  placeholder="请输入收款账户"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户银行" prop="paymentBank">
                <el-input
                  v-model="formData.paymentBank"
                  placeholder="请输入开户银行"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="微信支付商户号" prop="wechatPayMerchantId">
                <el-input
                  v-model="formData.wechatPayMerchantId"
                  placeholder="请输入微信支付商户号"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="支付宝商户号" prop="alipayMerchantId">
                <el-input
                  v-model="formData.alipayMerchantId"
                  placeholder="请输入支付宝商户号"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="收款二维码" prop="paymentQrCode">
            <div class="disabled-upload-section">
              <FileUpload
                v-model="paymentQrCodeFiles"
                :upload-type="'PAYMENT_QR'"
                :upload-source="'WEB'"
                :multiple="false"
                :max-size="2"
                :allowed-types="['jpg', 'jpeg', 'png']"
                list-type="picture-card"
                :disabled="true"
                tip="请上传收款二维码图片，支持jpg、jpeg、png格式，最大2MB，只能上传一个文件"
                @on-success="handlePaymentQrCodeSuccess"
                @on-error="handleUploadError"
              />
              <div class="disabled-tip">
                <el-icon><InfoFilled /></el-icon>
                <span>请物业公司通过审核后再补齐图片信息！</span>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="在线支付链接" prop="paymentLink">
            <el-input
              v-model="formData.paymentLink"
              placeholder="请输入在线支付链接"
              clearable
            />
          </el-form-item>
        </div>

        <!-- 其他信息 -->
        <div class="form-section">
          <h3 class="section-title">其他信息</h3>
          <el-form-item label="公司Logo" prop="companyLogo">
            <div class="disabled-upload-section">
              <FileUpload
                v-model="companyLogoFiles"
                :upload-type="'COMPANY_LOGO'"
                :upload-source="'WEB'"
                :multiple="false"
                :max-size="2"
                :allowed-types="['jpg', 'jpeg', 'png']"
                list-type="picture-card"
                :disabled="true"
                tip="请上传公司Logo图片，支持jpg、jpeg、png格式，最大2MB，只能上传一个文件"
                @on-success="handleCompanyLogoSuccess"
                @on-error="handleUploadError"
              />
              <div class="disabled-tip">
                <el-icon><InfoFilled /></el-icon>
                <span>请物业公司通过审核后再补齐图片信息！</span>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            <el-icon><Check /></el-icon>
            提交注册
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button @click="handleCancel">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
        </div>
      </el-form>
      </el-card>
    </div>

    <!-- 页面底部 -->
    <div class="page-footer">
      <p>&copy; 2024 智慧社区管理系统. All rights reserved.</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { House, Check, Refresh, Close, InfoFilled } from '@element-plus/icons-vue'
import { propertyCompanyApi } from '@/api/property/propertyCompany'
import type { PropertyCompanyFormData } from '@/types/property'
import FileUpload from '@/components/FileUpload.vue'
import type { UploadUserFile } from 'element-plus'

// 路由相关
const router = useRouter()

// 响应式数据
const loading = ref(false)
const formRef = ref()

// 文件上传相关
const paymentQrCodeFiles = ref<UploadUserFile[]>([])
const companyLogoFiles = ref<UploadUserFile[]>([])

// 表单数据
const formData = reactive<PropertyCompanyFormData>({
  companyName: '',
  companyCode: '',
  creditCode: '',
  businessLicense: '',
  legalRepresentative: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  email: '',
  address: '',
  description: '',
  establishedDate: '',
  registeredCapital: undefined,
  serviceScope: '',
  qualificationLevel: '',
  paymentQrCode: '',
  paymentAccount: '',
  paymentBank: '',
  paymentLink: '',
  wechatPayMerchantId: '',
  alipayMerchantId: '',
  companyLogo: '',
  introduction: '',
  businessHours: '',
  serviceHotline: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  companyName: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 2, max: 100, message: '公司名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  // 公司编码由系统自动生成，无需验证
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' },
    { min: 2, max: 50, message: '联系人长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入公司地址', trigger: 'blur' }
  ],
  serviceHotline: [
    { pattern: /^(1[3-9]\d{9}|0\d{2,3}-?\d{7,8}|400-?\d{3}-?\d{4}|800-?\d{3}-?\d{4})$/, message: '服务热线格式不正确，支持手机号或常见热线号格式', trigger: 'blur' }
  ],
  qualificationLevel: [
    { required: true, message: '请选择资质等级', trigger: 'change' }
  ]
}

// 收款二维码上传成功处理
const handlePaymentQrCodeSuccess = (response: any, file: any, fileList: UploadUserFile[]) => {
  if (response && response.data && response.data.fileUrl) {
    formData.paymentQrCode = response.data.fileUrl
  }
}

// 公司Logo上传成功处理
const handleCompanyLogoSuccess = (response: any, file: any, fileList: UploadUserFile[]) => {
  if (response && response.data && response.data.fileUrl) {
    formData.companyLogo = response.data.fileUrl
  }
}

// 文件上传错误处理
const handleUploadError = (error: Error, file: any, fileList: UploadUserFile[]) => {
  console.error('文件上传失败:', error)
  ElMessage.error('文件上传失败，请重试')
}

// 提交注册
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    loading.value = true
    await propertyCompanyApi.registerPropertyCompany(formData)
    
    // 跳转到注册成功页面，传递公司名称参数
    router.push({
      path: '/property/company/register-success',
      query: { companyName: formData.companyName }
    })
  } catch (error: any) {
    console.error('注册失败:', error)
    ElMessage.error(error.message || '注册失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields()
  Object.assign(formData, {
    companyName: '',
    companyCode: '',
    creditCode: '',
    businessLicense: '',
    legalRepresentative: '',
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    email: '',
    address: '',
    description: '',
    establishedDate: '',
    registeredCapital: undefined,
    serviceScope: '',
    qualificationLevel: '',
    paymentQrCode: '',
    paymentAccount: '',
    paymentBank: '',
    paymentLink: '',
    wechatPayMerchantId: '',
    alipayMerchantId: '',
    companyLogo: '',
    introduction: '',
    businessHours: '',
    serviceHotline: '',
    remark: ''
  })
  
  // 清空文件列表
  paymentQrCodeFiles.value = []
  companyLogoFiles.value = []
}

// 取消注册
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消注册吗？未保存的信息将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleReset()
    ElMessage.info('已取消注册')
  }).catch(() => {
    // 用户取消
  })
}

// 页面初始化
onMounted(() => {
  // 可以在这里添加一些初始化逻辑
})
</script>

<style scoped>
.property-company-register-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

/* 禁用上传区域样式 */
.disabled-upload-section {
  position: relative;
}

.disabled-upload-section .el-upload {
  opacity: 0.6;
  pointer-events: none;
}

.disabled-tip {
  display: flex;
  align-items: center;
  margin-top: 8px;
  padding: 8px 12px;
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  color: #409eff;
  font-size: 14px;
}

.disabled-tip .el-icon {
  margin-right: 6px;
  font-size: 16px;
}

/* 背景动画 */
.property-company-register-page::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="rgba(255,255,255,0.1)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
  opacity: 0.3;
  animation: float 20s ease-in-out infinite;
}

/* 页面头部 */
.page-header {
  padding: 40px 0 20px;
  text-align: center;
  color: white;
  z-index: 1;
  position: relative;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.logo-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  gap: 12px;
}

.logo-icon {
  font-size: 32px;
  color: white;
}

.system-title {
  font-size: 28px;
  font-weight: bold;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.page-title h2 {
  font-size: 36px;
  font-weight: bold;
  margin: 0 0 8px 0;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.page-title p {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

/* 注册容器 */
.register-container {
  flex: 1;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 0 20px 40px;
  z-index: 1;
  position: relative;
}

.register-card {
  width: 100%;
  max-width: 1200px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  animation: slideIn 0.6s ease-out;
}

.register-form {
  padding: 30px;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.form-actions .el-button {
  margin: 0 10px;
  min-width: 120px;
}

/* 页面底部 */
.page-footer {
  padding: 20px;
  text-align: center;
  color: white;
  z-index: 1;
  position: relative;
}

.page-footer p {
  margin: 0;
  opacity: 0.8;
  font-size: 14px;
}

/* 动画 */
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    padding: 20px 0 10px;
  }
  
  .system-title {
    font-size: 24px;
  }
  
  .page-title h2 {
    font-size: 28px;
  }
  
  .register-container {
    padding: 0 10px 20px;
  }
  
  .register-form {
    padding: 20px;
  }
  
  .form-section {
    padding: 15px;
  }
  
  .form-actions .el-button {
    margin: 5px;
    min-width: 100px;
  }
}

/* 表单提示样式 */
.form-tip {
  display: flex;
  align-items: center;
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.form-tip .el-icon {
  margin-right: 4px;
  font-size: 14px;
}
</style> 